﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WeatheRx.Data;

namespace WeatheRx.Managers
{
    public interface IUtilityManager
    {
        List<Utility> GetUtilities(int? agencyId);

        List<Account> GetUtilityAccounts(int? applicantId);

        void StoreAccounts(List<Account> accounts);
    }

    public class UtilityManager : IUtilityManager
    {
        public List<Utility> GetUtilities(int? agencyId)
        {
            List<Utility> result;
            using (var db = new HWAPEntities())
            {
                result = db.Utilities.Where(x => x.AgencyId == agencyId).ToList();
            }
            return result;
        }

        public List<Account> GetUtilityAccounts(int? applicantId)
        {
            List<Account> result;
            using (var db = new HWAPEntities())
            {
                result = db.Accounts.Where(x => x.ApplicantId == applicantId).ToList();
            }
            return result;
        }

        public void StoreAccounts(List<Account> accounts)
        {
            using (var db = new HWAPEntities())
            {
                var addList = accounts.Where(x => x.AccountId > 0).ToList();
                var updateList = accounts.Where(x => x.AccountId == 0).ToList();
                updateList.ForEach(x =>
                {
                    var firstOrDefault = db.Accounts.FirstOrDefault(y => y.AccountId == x.AccountId);
                    if (firstOrDefault != null)
                    {
                        Mapper.Map(x, firstOrDefault);
                    }
                    else
                    {
                        addList.Add(x);
                    }
                });
                db.Accounts.AddRange(addList);
                db.SaveChanges();
            }
        }
    }
}